package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisWorker {
private static final long BEGIN_TIME = 1640995200;
private static final long COUNT_BITS = 32;

    private StringRedisTemplate stringRedisTemplate;

    public RedisWorker(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }
   public long nextId(String keyPrefix){
//        1.生成时间戳
       LocalDateTime now = LocalDateTime.now();
       long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
       long timestamp = nowSecond - BEGIN_TIME;
//       2.生成序列号
//       2.1生成当前日期
       String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//       2.2自增长 创建一个key,然后自增value，从0开始
       Long key = stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + date);


       return timestamp<<COUNT_BITS | key;
   }

}
